import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  // 超时时间
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 携带的是请求信息
    // 这个函数通常配置请求头，携带token
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code !== 10000) {
      Message({
        type: 'warning',
        message: response.data.msg
      })
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  error => {
    console.log(error)
    if (error.response.status === 401) {
      // token过期
      // 清空token,跳转到登录页
      store.commit('user/removeToken')
      router.push('/login')
    }
    Message({
      type: 'warning',
      message: error.response.data.msg
    })
    return Promise.reject(error)
  }
)

export default service
